<template>
  <div class="auth-container">
    <!-- 背景装饰元素 -->
    <div class="bg-circle circle-1"></div>
    <div class="bg-circle circle-2"></div>
    <div class="bg-circle circle-3"></div>

    <!-- 登录卡片居中显示 -->
    <div class="login-card">
      <!-- 品牌Logo区域 -->
      <div class="brand-section">
        <div class="brand-logo">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="60" height="60">
            <path
              fill="#165dff"
              d="M12,23C5.9,23,1,18.1,1,12S5.9,1,12,1s11,4.9,11,11S18.1,23,12,23z M12,3c-5,0-9,4,9,9s4,9,9,9s9-4,9-9S17,3,12,3z"
            />
            <path
              fill="#0e42d2"
              d="M12,16c-2.2,0-4-1.8-4-4s1.8-4,4-4s4,1.8,4,4S14.2,16,12,16z M12,10c-1.1,0-2,0.9-2,2s0.9,2,2,2s2-0.9,2-2S13.1,10,12,10z"
            />
          </svg>
        </div>
        <h1 class="brand-name">灵犀智影</h1>
        <p class="brand-slogan">脚本到成片全程智能驱动</p>
      </div>

      <!-- 登录表单 -->
      <div class="pc-sms-login">
        <!-- 标题栏 -->
        <div class="head-box">
          <div class="title-bar">
            <div
              class="title"
              :class="{ active: currentTab === 'smsLogin' }"
              @click="currentTab = 'smsLogin'"
            >
              短信登录
            </div>
            <div
              class="title"
              :class="{ active: currentTab === 'accountLogin' }"
              @click="currentTab = 'accountLogin'"
            >
              账号登录
            </div>
          </div>
          <div class="subtitle">未注册的手机号，验证后自动注册账号</div>
        </div>

        <!-- 表单区域 -->
        <el-form
          ref="smsLoginForm"
          :model="form"
          :rules="currentRules"
          label-width="50px"
          label-position="right"
        >
          <!-- 手机号 -->
          <el-form-item prop="mobile">
            <el-input
              v-model="form.mobile"
              placeholder="请输入手机号"
              prefix-icon="el-icon-phone"
              @input="handlePhoneInput"
              class="elegant-input"
            >
              <template #suffix>
                <el-button
                  type="text"
                  :disabled="!isPhoneValid || countdown > 0"
                  @click="handleSendCode"
                  class="code-btn"
                >
                  {{ countdown > 0 ? `${countdown}s后重新获取` : "获取验证码" }}
                </el-button>
              </template>
            </el-input>
          </el-form-item>

          <!-- 验证码 -->
          <el-form-item prop="code" v-if="currentTab === 'smsLogin'">
            <el-input
              v-model="form.code"
              placeholder="请输入验证码"
              prefix-icon="el-icon-lock"
              class="elegant-input"
            />
          </el-form-item>

          <!-- 密码 -->
          <el-form-item prop="password" v-if="currentTab === 'accountLogin'">
            <el-input
              type="password"
              v-model="form.password"
              placeholder="请输入密码"
              prefix-icon="el-icon-lock"
              class="elegant-input"
              show-password
            >
              <template #suffix>
                <el-button type="text" @click="handleForgotPassword" class="forgot-btn">
                  忘记密码
                </el-button>
              </template>
            </el-input>
          </el-form-item>

          <!-- 协议提示 -->
          <div class="agreement-tip">
            <el-checkbox v-model="agreeStatus" class="agreement-check">
              我已阅读并同意
            </el-checkbox>
            <el-link type="primary" @click="agreementVisible = true">《用户协议》</el-link>
            <span>和</span>
            <el-link type="primary" @click="agreementVisible = true">《隐私条款》</el-link>
          </div>

          <!-- 登录按钮 -->
          <el-form-item>
            <el-button
              type="primary"
              class="login-btn"
              @click="handleLogin"
              :loading="loginLoading"
            >
              登录
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 底部链接区域 -->
      <div class="footer-links">
        <a href="#" class="footer-link">关于我们</a>
        <span class="divider">|</span>
        <a href="#" class="footer-link">帮助中心</a>
        <span class="divider">|</span>
        <a href="#" class="footer-link">联系我们</a>
      </div>
    </div>

    <!-- 版权信息 -->
    <div class="copyright">
      © 2025 灵犀智影 版权所有 | 当前时间：<span class="time-highlight">{{ formattedTime }}</span>
    </div>
    <!-- 协议弹窗 -->
    <el-dialog
      v-model="agreementVisible"
      title="用户协议与隐私条款"
      width="80%"
      max-width="700px"
      custom-class="agreement-dialog"
    >
      <div class="agreement-content">
        <h3>欢迎使用灵犀智影</h3>
        <p>在您开始使用我们的服务之前，请仔细阅读以下协议：</p>

        <div class="agreement-section">
          <h4>1. 服务条款的接受</h4>
          <p>
            当您使用本系统时，表示您已充分阅读、理解并同意接受本协议的全部内容，包括我们随时对协议所做的任何修改。
          </p>
        </div>

        <div class="agreement-section">
          <h4>2. 合法使用</h4>
          <p>
            您承诺使用本系统仅用于合法目的，不得从事任何违反国家法律法规的活动。未经授权不得访问或试图访问本系统的任何非公开部分。
          </p>
        </div>

        <div class="agreement-section">
          <h4>3. 账号安全</h4>
          <p>
            您需要妥善保管账号和密码，所有操作均视为您本人操作。如发现任何非法使用账号的情况，请立即通知我们。
          </p>
        </div>

        <div class="agreement-section">
          <h4>4. 隐私保护</h4>
          <p>我们承诺保护您的个人信息安全：</p>
          <ul>
            <li>我们仅在提供服务所必需时收集您的个人信息</li>
            <li>未经您同意，我们不会向第三方提供您的个人信息</li>
            <li>我们采取行业标准的安全措施保护您的数据</li>
          </ul>
        </div>

        <div class="agreement-section">
          <h4>5. 免责声明</h4>
          <p>
            对于因不可抗力（如自然灾害、政府行为等）或非因我们过错造成的服务中断或数据丢失，我们不承担相关责任。
          </p>
        </div>

        <div class="agreement-section">
          <h4>6. 协议变更</h4>
          <p>
            我们保留随时修改本协议的权利。修改后的协议将在发布后生效，请您定期查阅最新协议内容。
          </p>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="agreementVisible = false">取消</el-button>
          <el-button type="primary" @click="agreeProtocol">同意并继续</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted } from "vue";
import { ElMessage, ElForm } from "element-plus";
import AuthUtil from "@/api/member/auth";
import { useRouter, useRoute } from "vue-router";
import { useUserStore, UserInfo } from "@/store/user";

// 1. 基础状态
const currentTab = ref<"smsLogin" | "accountLogin">("smsLogin");
const form = reactive({
  mobile: "",
  code: "",
  password: "",
});
const smsLoginForm = ref<InstanceType<typeof ElForm>>();
const loginLoading = ref(false);
const countdown = ref(0);
const agreementVisible = ref(false);
const agreeStatus = ref(false);

// 2. 表单校验规则
const phoneReg = /^1[3-9]\d{9}$/;
const smsRules = reactive({
  mobile: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { pattern: phoneReg, message: "请输入正确的手机号", trigger: "blur" },
  ],
  code: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { min: 4, max: 4, message: "验证码为4位数字", trigger: "blur" },
  ],
});

const accountRules = reactive({
  mobile: [
    { required: true, message: "请输入账号", trigger: "blur" },
    {
      validator(rule: any, value: string, callback: any) {
        if (phoneReg.test(value) || /^[a-zA-Z0-9_-]{4,16}$/.test(value)) {
          callback();
        } else {
          callback(new Error("请输入正确的手机号或4-16位账号"));
        }
      },
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "密码长度为6-20位", trigger: "blur" },
  ],
});

// 3. 计算属性
const currentRules = computed(() => {
  return currentTab.value === "smsLogin" ? smsRules : accountRules;
});

const isPhoneValid = computed(() => phoneReg.test(form.mobile));

// 4. 方法
// 手机号输入过滤
const handlePhoneInput = () => {
  form.mobile = form.mobile.replace(/\D/g, ""); // 只保留数字
};

// 发送验证码
const handleSendCode = async () => {
  if (!isPhoneValid.value) {
    ElMessage.warning(" 请输入正确的手机号");
    return;
  }

  try {
    const purePhone = form.mobile.trim();
    await AuthUtil.sendSmsCode(purePhone, 1); // 复用uniapp的api
    countdown.value = 60;
    const timer = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) clearInterval(timer);
    }, 1000);
    ElMessage.success(" 验证码发送成功");
  } catch (error: any) {
    console.error(" 发送验证码失败:", error);
    ElMessage.error(error.data?.msg || "验证码发送失败，请重试");
  }
};

// 忘记密码（账号登录时）
const handleForgotPassword = () => {
  console.log(" 跳转到忘记密码页面逻辑");
};

// 协议处理
const agreeProtocol = () => {
  agreeStatus.value = true;
  agreementVisible.value = false;
  ElMessage.success(" 您已同意用户协议");
};

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();
// 登录逻辑
const handleLogin = async () => {
  // 1. 表单校验
  try {
    await smsLoginForm.value?.validate();
  } catch (error) {
    return;
  }

  // 2. 协议校验
  if (!agreeStatus.value) {
    ElMessage.warning(" 请先同意用户协议和隐私条款");
    return;
  }

  // 3. 提交登录
  loginLoading.value = true;
  const pureMobile = form.mobile.trim();

  try {
    let loginRes: any;
    if (currentTab.value === "smsLogin") {
      loginRes = await AuthUtil.smsLogin({
        mobile: pureMobile,
        code: form.code,
      });
    } else {
      loginRes = await AuthUtil.login({
        // 复用uniapp的登录逻辑
        mobile: pureMobile,
        password: form.password,
      });
    }

    if (loginRes.code === 0) {
      const userData: UserInfo = {
        phone: pureMobile,
        token: loginRes.data.accessToken,
        refreshToken: loginRes.data.refreshToken,
      };
      userStore.login(userData);
      ElMessage.success(" 登录成功");
      const redirectPath = (route.query.redirect as string) || "/";
      router.push(redirectPath);
    }
  } catch (error: any) {
    console.error(" 登录失败:", error);
    ElMessage.error(error.data?.msg || "登录失败，请重试");
  } finally {
    loginLoading.value = false;
  }
};
// 响应式数据：格式化后的时间字符串
const formattedTime = ref("");

// 格式化时间单位（补零）
const formatTimeUnit = (unit) => {
  return unit.toString().padStart(2, "0");
};

// 更新时间函数
const updateTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = formatTimeUnit(now.getMonth() + 1);
  const day = formatTimeUnit(now.getDate());
  const hours = formatTimeUnit(now.getHours());
  const minutes = formatTimeUnit(now.getMinutes());
  const seconds = formatTimeUnit(now.getSeconds());
  formattedTime.value = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 定时器变量
let timer: number = 0;

// 组件挂载时启动定时器
onMounted(() => {
  // 立即更新一次
  updateTime();
  // 每秒更新一次
  timer = setInterval(updateTime, 1000);
});

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer) clearInterval(timer);
});
</script>

<style scoped lang="scss">
.auth-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #f0f4ff 0%, #e6f0ff 100%);
  position: relative;
  overflow: hidden;
  padding: 20px;

  .bg-circle {
    position: absolute;
    border-radius: 50%;
    background: radial-gradient(circle, rgba(22, 93, 255, 0.1) 0%, transparent 70%);
    z-index: 0;

    &.circle-1 {
      width: 400px;
      height: 400px;
      top: -100px;
      left: -100px;
    }

    &.circle-2 {
      width: 600px;
      height: 600px;
      bottom: -150px;
      right: -150px;
    }

    &.circle-3 {
      width: 300px;
      height: 300px;
      bottom: 100px;
      left: 150px;
      background: radial-gradient(circle, rgba(14, 66, 210, 0.08) 0%, transparent 70%);
    }
  }

  .login-card {
    width: 100%;
    max-width: 480px;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 20px;
    box-shadow: 0 15px 50px rgba(22, 93, 255, 0.15);
    overflow: hidden;
    position: relative;
    z-index: 1;
    padding: 35px;
    border: 1px solid rgba(22, 93, 255, 0.1);

    .brand-section {
      text-align: center;
      margin-bottom: 35px;

      .brand-logo {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 88px;
        height: 88px;
        background: rgba(22, 93, 255, 0.1);
        border-radius: 50%;
        margin: 0 auto 15px;
        padding: 14px;
        border: 1px solid rgba(22, 93, 255, 0.15);
      }

      .brand-name {
        font-size: 24px;
        font-weight: 700;
        color: #165dff;
        margin-bottom: 8px;
        letter-spacing: 0.5px;
      }

      .brand-slogan {
        font-size: 14px;
        color: #6c757d;
        margin: 0;
      }
    }
  }

  .pc-sms-login {
    padding: 0;

    .head-box {
      margin-bottom: 30px;

      .title-bar {
        display: flex;
        gap: 40px;
        margin-bottom: 15px;
        justify-content: center;

        .title {
          font-size: 18px;
          font-weight: 600;
          color: #6c757d;
          cursor: pointer;
          padding-bottom: 8px;
          position: relative;
          transition: all 0.3s ease;

          &::after {
            content: "";
            position: absolute;
            bottom: 0;
            left: 50%;
            width: 0;
            height: 3px;
            background: #165dff;
            border-radius: 2px;
            transform: translateX(-50%);
            transition: width 0.3s ease;
          }

          &:hover {
            color: #165dff;
          }

          &.active {
            color: #165dff;

            &::after {
              width: 100%;
            }
          }
        }
      }

      .subtitle {
        color: #6c757d;
        font-size: 14px;
        text-align: center;
      }
    }

    .el-form {
      width: 100%;

      .el-form-item {
        margin-bottom: 28px;

        &:last-child {
          margin-bottom: 0;
        }
      }

      .agreement-tip {
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 15px 0 25px;
        font-size: 14px;
        color: #666;

        .agreement-check {
          margin-right: 6px;
        }

        .el-link {
          margin: 0 4px;
          font-size: 14px;
        }
      }

      .elegant-input {
        :deep(.el-input__wrapper) {
          border-radius: 12px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
          padding: 0 18px;
          transition: all 0.3s;
          background: rgba(255, 255, 255, 0.9);
          height: 48px;

          &:hover {
            box-shadow: 0 2px 12px rgba(22, 93, 255, 0.15);
          }

          &.is-focus {
            box-shadow: 0 2px 12px rgba(22, 93, 255, 0.25);
          }
        }

        :deep(.el-input__prefix) {
          display: flex;
          align-items: center;
          margin-right: 12px;

          i {
            color: #165dff;
            font-size: 18px;
          }
        }
      }

      .code-btn {
        color: #165dff;
        font-weight: 500;
        transition: all 0.3s;
        font-size: 14px;

        &:not(:disabled):hover {
          color: #0e42d2;
          transform: translateY(-1px);
        }

        &:disabled {
          color: #a0a0a0;
          cursor: not-allowed;
        }
      }

      .forgot-btn {
        color: #6c757d;
        font-size: 13px;
        transition: all 0.3s;

        &:hover {
          color: #165dff;
          transform: translateY(-1px);
        }
      }

      .login-btn {
        width: 100%;
        height: 52px;
        font-size: 17px;
        font-weight: 600;
        border-radius: 12px;
        background: linear-gradient(90deg, #165dff, #0e42d2);
        border: none;
        box-shadow: 0 4px 15px rgba(22, 93, 255, 0.3);
        transition: all 0.3s;
        letter-spacing: 1px;
        margin-top: 15px;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 6px 18px rgba(22, 93, 255, 0.4);
          background: linear-gradient(90deg, #1e6bff, #1650e0);
        }

        &:active {
          transform: translateY(0);
          box-shadow: 0 3px 10px rgba(22, 93, 255, 0.3);
        }
      }
    }
  }

  .footer-links {
    margin-top: 30px;
    text-align: center;
    padding-top: 20px;
    border-top: 1px solid rgba(0, 0, 0, 0.05);

    .footer-link {
      color: #6c757d;
      text-decoration: none;
      font-size: 14px;
      transition: all 0.3s;
      margin: 0 10px;

      &:hover {
        color: #165dff;
      }
    }

    .divider {
      color: #d0d0d0;
      font-size: 12px;
    }
  }

  .copyright {
    position: absolute;
    bottom: 20px;
    width: 100%;
    text-align: center;
    font-size: 12px;
    color: rgba(0, 0, 0, 0.4);
  }
}

:deep(.agreement-dialog) {
  border-radius: 16px;
  box-shadow: 0 15px 50px rgba(22, 93, 255, 0.2);
  overflow: hidden;

  .el-dialog__header {
    background: linear-gradient(to right, #165dff, #0e42d2);
    margin: 0;
    padding: 20px;

    .el-dialog__title {
      color: white;
      font-weight: 600;
      font-size: 18px;
    }

    .el-dialog__headerbtn {
      .el-dialog__close {
        color: white;
      }
    }
  }

  .agreement-content {
    max-height: 55vh;
    overflow-y: auto;
    padding: 20px 25px;
    color: #444;

    h3 {
      color: #165dff;
      text-align: center;
      margin-top: 0;
      margin-bottom: 20px;
      font-size: 22px;
    }

    p {
      line-height: 1.8;
      margin-bottom: 15px;
    }

    .agreement-section {
      margin-bottom: 25px;

      h4 {
        color: #0e42d2;
        margin-top: 0;
        margin-bottom: 10px;
        font-size: 17px;
        position: relative;
        padding-left: 18px;

        &::before {
          content: "";
          position: absolute;
          left: 0;
          top: 9px;
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background: #165dff;
        }
      }

      ul {
        padding-left: 25px;
        margin-top: 8px;

        li {
          margin-bottom: 8px;
          line-height: 1.6;
        }
      }
    }
  }

  .el-dialog__footer {
    padding: 20px;
    background: #f9faff;
    border-top: 1px solid #eee;

    .dialog-footer {
      display: flex;
      justify-content: center;
      gap: 20px;

      .el-button {
        min-width: 120px;
        height: 42px;
        font-size: 16px;
        border-radius: 10px;

        &:last-child {
          background: linear-gradient(90deg, #165dff, #0e42d2);
          border: none;
          color: white;

          &:hover {
            background: linear-gradient(90deg, #1e6bff, #1650e0);
          }
        }
      }
    }
  }
}
</style>
